package com.kid.keep.interceptor;

import com.kid.keep.common.SessionStore;
import com.kid.keep.common.UserSubject;
import com.kid.keep.dto.AppDTO;
import com.kid.keep.dto.UserDTO;
import com.kid.keep.exception.CommonException;
import com.kid.keep.enums.CommonExceptionEnum;
import com.kid.keep.service.IAppService;
import com.kid.keep.service.IUserService;
import com.honeybee.cloud.framework.base.exception.authorize.NoAuthorizeExceptionBase;
import com.honeybee.cloud.framework.base.exception.authorize.NoAuthorizeExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Description 检验用户是否授权过
 * @Author JOHN
 * @Create 2020-01-02
 * @Since 1.0.0
 */
@Slf4j
public class HeaderInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;
    @Autowired
    private IAppService appService;
    private final String USER_ID = "USER_ID";
    private final String APP_ID = "APP_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String userIdStr = request.getHeader(USER_ID);
        String appIdStr = request.getHeader(APP_ID);
        if (StringUtils.isBlank(userIdStr) || StringUtils.isBlank(appIdStr)) {
            throw NoAuthorizeExceptionBase.getInstance(NoAuthorizeExceptionEnum.NO_AUTHORIZE);
        }
        AppDTO appDTO=getApp(appIdStr);
        UserDTO userDTO=getUser(userIdStr,appDTO);
        saveSession(userDTO);
        return true;
    }

    private AppDTO getApp(String appId){
        AppDTO appDTO=appService.findByWxAppId(appId);
        if(Objects.isNull(appDTO)){
            throw NoAuthorizeExceptionBase.getInstance(NoAuthorizeExceptionEnum.NO_AUTHORIZE);
        }
        return appDTO;
    }

    private UserDTO getUser(String userIdStr,AppDTO appDTO){
        Long userId;
        try {
            userId = Long.parseLong(userIdStr);
        } catch (Exception e) {
            log.error("类型转换异常", e);
            throw CommonException.getInstance(CommonExceptionEnum.HEADER);
        }
        UserDTO userDTO = userService.findByIdAndAppId(userId, appDTO.getId());
        if (Objects.isNull(userDTO)) {
            throw NoAuthorizeExceptionBase.getInstance(NoAuthorizeExceptionEnum.NO_AUTHORIZE);
        }
        return userDTO;
    }

    private void saveSession(UserDTO userDTO){
        UserSubject userSubject = new UserSubject(userDTO.getAppId(), userDTO.getId());
        SessionStore.saveSessionUser(userSubject);
    }
}
